﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Xml;

namespace ALinq.Mapping
{
    /// <summary>
    /// Represents the base class for mapping object.
    /// </summary>
    public abstract class ModelMapping
    {
        private Dictionary<string, object> values;

        internal ModelMapping(ModelMappingType modelMappingType)
        {
            //this.Document = doc;
            this.MappingType = modelMappingType;
            //this.XmlElement = doc.CreateElement(modelMappingType.ToString(), Namespace);
            this.values = new Dictionary<string, object>();
        }

        internal ModelMappingType MappingType
        {
            get;
            private set;
        }

        internal ModelMapping Parent
        {
            get;
            set;
        }

        /// <summary>
        ///  Set a attribute value which use to generate an XML mapping source.
        /// </summary>
        /// <typeparam name="T">Type of the attribute.</typeparam>
        /// <param name="member">The attribute member.</param>
        /// <param name="value">Value of the attribute.</param>
        protected void SetAttribute<T>(Expression<Func<T>> member, T value)
        {
            var memberInfo = ((MemberExpression)member.Body).Member;
            SetAttribute(memberInfo.Name, value);
        }

        /// <summary>
        /// Get a attribute value which use in the XML mappint source.
        /// </summary>
        /// <typeparam name="T">Type of the attribute.</typeparam>
        /// <param name="member">The attribute member.</param>
        /// <returns>Value of the attribute.</returns>
        protected T GetAttribute<T>(Expression<Func<T>> member)
        {
            var memberInfo = ((MemberExpression)member.Body).Member;
            object value;
            if (values.TryGetValue(memberInfo.Name, out value))
                return (T)value;

            return default(T);
        }

        /// <summary>
        /// Set a attribute value which use to generate an XML mapping source.
        /// </summary>
        /// <typeparam name="T">Type of the value</typeparam>
        /// <param name="name">The attribute name.</param>
        /// <param name="value">Value of the attribute.</param>
        protected void SetAttribute<T>(string name, T value)
        {
            if (typeof (T).IsValueType == false && value as object == null)
                values.Remove(name);

            values[name] = value;
        }

        internal Dictionary<string, object> Attributes
        {
            get { return this.values; }
        }


    }
}
